
// 不同对象的数据, 使用proxy的getter/setter方法,在getter中设置track, 在setter中添加trigger
// 通过抽离effect方法，可以设置不同的effect

let targetMap = new WeakMap();
let activeEffect = null;
const effect = (eff) => {
  activeEffect = eff;
  activeEffect();
  activeEffect = null;
};
const track = (target, key) => {
  if(activeEffect){
    let depsMap = targetMap.get(target);
    if (!depsMap) {
      depsMap = new Map();
      targetMap.set(target, depsMap);
    }
    let deps = depsMap.get(key);
    if (!deps) {
      deps = new Set();
      depsMap.set(key, deps);
    }
    deps.add(activeEffect);
  }
};

const trigger = (target, key) => {
  let depsMap = targetMap.get(target);
  if (!depsMap) {
    return;
  }
  let deps = depsMap.get(key);
  if (deps) {
    deps.forEach((effect) => {
      effect();
    });
  }
};
const reactive = (target) => {
  const handler = {
    get(target, key, receiver){
      console.log(`read get data: ${key}`);
      const result = Reflect.get(target, key, receiver);
      track(target, key);
      return result;
    },
    set(target, key, value, receiver){
      console.log(`set data: ${key}`);
      const oldValue = target[key];
      const result = Reflect.set(target, key, value, receiver);
      if(value != oldValue){
        trigger(target, key);
      }
      return result;
    }
  }
  return new Proxy(target, handler)
}

let product = reactive({
  price: 20,
  quantity: 3,
}),
  total = 0,
  car = reactive({
    price: 123455,
    quantity:2
  });

effect(()=>{
  total = product.price * product.quantity
});

console.log(`${total}`);
product.price = 87;
console.log(`${total}`);
product.quantity = 5;
effect(()=>{
  total = product.price * 0.8
});
console.log(`${total}`);
effect(()=>{
  total = car.price * car.quantity
});
console.log(`${total}`);
car.quantity = 5;
console.log(`${total}`);
